import 'dart:math';

import 'package:flutter/material.dart';

class JoyStick extends StatefulWidget {
  JoyStick({required this.onJoyStickListener});

  final Function(Offset) onJoyStickListener;

  @override
  _JoyStickState createState() => _JoyStickState();
}

class _JoyStickState extends State<JoyStick> {
  Offset mySet = Offset.zero;
  final double bgSize = 120;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: bgSize,
      height: bgSize,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(bgSize / 2),
        color: const Color(0x88ffffff),
      ),
      child: GestureDetector(
        onPanStart: _onPanStart,
        onPanUpdate: _onPanUpdate,
        onPanEnd: _onPanEnd,
        child: Center(
          child: Transform.translate(
            offset: mySet,
            //摇杆
            child: SizedBox(
              width: bgSize / 2,
              height: bgSize / 2,
              child: Container(
                decoration: BoxDecoration(
                  color: const Color(0xccffffff),
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void _onPanStart(DragStartDetails details) {
    _updateJoystick(details.localPosition, true);
  }

  void _onPanUpdate(DragUpdateDetails details) {
    _updateJoystick(details.localPosition, true);
  }

  void _onPanEnd(DragEndDetails details) {
    _updateJoystick(Offset(bgSize / 2, bgSize / 2), false);
  }

  void _updateJoystick(Offset offset, bool flag) {
    Offset newOffset = offset - Offset(bgSize / 2, bgSize / 2);
    Offset temp = Offset.fromDirection(
        newOffset.direction, min(bgSize / 2, newOffset.distance));
    if (flag == true) {
      widget.onJoyStickListener(temp);
    }else{
      widget.onJoyStickListener(Offset.zero);
    }
    setState(() {
      mySet = temp;
    });
  }
}
